package com.frxuexi.task.view

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.frxuexi.lib_base.MyTitleBar
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.room.Task
import com.frxuexi.task.intent.TaskIntent
import com.frxuexi.task.viewmodel.TaskViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@Composable
fun TaskPage(navHostController: NavHostController, vm: TaskViewModel = hiltViewModel()) {

    var tname by remember {
        mutableStateOf("")
    }
    var desp by remember {
        mutableStateOf("")
    }
    val name = MMKV.defaultMMKV().decodeString("name", "")

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*>->{
                        Log.i("===","任务提交成功${it.data}")
                        navHostController.popBackStack()
                    }else->{}
                }
            }
        }
    })

    Column {
        MyTitleBar(title = "任务", navHostController = navHostController)
        Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = tname,
                onValueChange = { tname = it },
                label = { Text(text = "任务名称") })
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = desp,
                onValueChange = { desp = it },
                label = { Text(text = "任务描述") })
            Button(modifier = Modifier.fillMaxWidth(), onClick = {
                val time =
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                val task = Task(null, tname, desp, name, time, "已提交")
                vm.sendIntent(TaskIntent.commitTask(task))
            }) {
                Text(text = "提交任务")
            }
        }

    }
}